package com.pansoft.openplanet.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.util.DecimalDigitsInputFilter;
import com.pansoft.openplanet.util.TCMathUtil;
import com.pansoft.openplanet.util.TCStringUtil;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 卖币
 * Created by will on 18-3-28.
 */

public class SellTCActivity extends TCBaseActivity implements View.OnClickListener {

    private ConstraintLayout clPayDetail;//底部结算详情，默认显示，当输入的金额符合限额时显示
    private TextView tvEthAmount, tvMoneyAmount;//底部结算详情的金额，tvETHAmount数字币的数量
    private TextView tvSellButton;
    private TextView tvRestrictAmount, tvRestrictAmountRepeat;//限额，和下方的交易限额
    private double exchangeRate = 3302d;//买家提供的兑换比率，1数字币兑换exchangeRate人民币
    private double moneyAmount, ethAmount;
    private double minEth = 2, maxEth = 4;
    private boolean firstEditTextHasFocus = false;
    private PopupWindow purchasePopup;
    private String paymentMethod = ResStringUtil.getString(R.string.open_planet_we_chat);
    private TextView tvPayment;
    private ImageView ivChoose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_activity_buy_tc);

        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_silver));
        initView();
    }

    private void initView() {

        TextView tvExchangeRate = (TextView) findViewById(R.id.tv_price);

        tvRestrictAmount = (TextView) findViewById(R.id.tv_restrict_amount);
        tvRestrictAmount.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_limit_silver));
        tvRestrictAmountRepeat = (TextView) findViewById(R.id.tv_restrict_amount_repeat);
        tvRestrictAmountRepeat.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_transaction_limit_silver));

        TextView tvWantAmount = (TextView) findViewById(R.id.tv_want_amount);
        tvWantAmount.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_sell_how_mach));

        TextView tvLocalMoney = (TextView) findViewById(R.id.tv_local_money);
        tvLocalMoney.setText(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_silver_diamond));
        final EditText etEthAmount = (EditText) findViewById(R.id.et_local_money_amount);
        etEthAmount.setHint(ResStringUtil.getString(R.string.open_planet_asset_selltc_enter_sell_amount));
        etEthAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8)});
        etEthAmount.setCursorVisible(false);
        TextView tvBCMoney = (TextView) findViewById(R.id.tv_block_chain_money);
        tvBCMoney.setText("CNY");
        final EditText etMoneyAmount = (EditText) findViewById(R.id.et_block_chain_money_amount);
        etMoneyAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2)});
        etMoneyAmount.setHint(ResStringUtil.getString(R.string.open_planet_asset_selltc_sell_amount));

        clPayDetail = (ConstraintLayout) findViewById(R.id.cl_pay_detail);
        clPayDetail.setVisibility(View.INVISIBLE);
        TextView tvEthIntro = (TextView) findViewById(R.id.tv_pay);
        tvEthIntro.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_sell_out));
        TextView tvMoneyIntro = (TextView) findViewById(R.id.tv_pay_second);
        tvMoneyIntro.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_receipt));

        tvPayment = (TextView) findViewById(R.id.tv_payment_choose);
        ivChoose = (ImageView) findViewById(R.id.iv_more);
        tvPayment.setOnClickListener(this);
        ivChoose.setOnClickListener(this);

        tvEthAmount = (TextView) findViewById(R.id.tv_pay_amount);
        tvEthAmount.setTextColor(getResources().getColor(R.color.tc_orange_color));

        tvMoneyAmount = (TextView) findViewById(R.id.tv_pay_second_amount);
        tvSellButton = (TextView) findViewById(R.id.tv_buy);
        tvSellButton.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_sell_now));
        tvSellButton.setOnClickListener(this);
        tvSellButton.setClickable(false);
        tvSellButton.setBackgroundColor(getResources().getColor(R.color.gray_light_bottom_button));

        etEthAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    etEthAmount.setCursorVisible(true);
                    firstEditTextHasFocus = true;
                } else {
                    firstEditTextHasFocus = false;
                }
            }
        });

        etEthAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (firstEditTextHasFocus) {//本editText获取焦点
                    if (!editable.toString().equals("") || editable.toString().startsWith(".")) {//输入不为""

                        if (!TCStringUtil.inputIsNumber(editable.toString())) {
                            ToastUtil.showToast(SellTCActivity.this, ResStringUtil.getString(R.string.open_planet_asset_selltc_input_illegal));
                            etEthAmount.setText("");
                            return;
                        }

//                        String text =etEthAmount.getText().toString();
//                        if (text.matches("^[-+]?(([0-9]+)(.)?|(.)?)$"))

                        ethAmount = new BigDecimal(etEthAmount.getText().toString()).doubleValue();
                        //输入的数字币数量乘以汇率得到金额，
                        moneyAmount = TCMathUtil.mul(ethAmount, exchangeRate);
                        //金额显示为两位小数，且不表示为科学计数法
                        etMoneyAmount.setText(new DecimalFormat("0.00").format(TCMathUtil.bigFormat(moneyAmount, 2)));
                        if (ethAmount >= minEth && ethAmount <= maxEth) {
                            //如果数字币在限额范围内，则显示底部详情，可以点击购买
                            tvRestrictAmountRepeat.setTextColor(getResources().getColor(R.color.tc_blue_color));
                            clPayDetail.setVisibility(View.VISIBLE);
                            tvMoneyAmount.setText(new DecimalFormat("0.00").format(TCMathUtil.bigFormat(moneyAmount, 2)) + " CNY");
                            tvEthAmount.setText(new DecimalFormat("0.00000000").format(ethAmount) + " "+ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_silver_diamond));
                            tvSellButton.setBackgroundColor(getResources().getColor(R.color.tc_blue_color));
                            tvSellButton.setClickable(true);
                        } else {
                            //数字币不在限额，则“交易限额”显示为红色，底部不可点击
                            tvRestrictAmountRepeat.setTextColor(getResources().getColor(R.color.tc_red_color));
                            clPayDetail.setVisibility(View.INVISIBLE);
                            tvSellButton.setBackgroundColor(getResources().getColor(R.color.gray_light_bottom_button));
                            tvSellButton.setClickable(false);
                        }
                    } else {//输入为"",则不进行数值计算，金额也设为"",限额、底部都设为默认
                        etMoneyAmount.setText("");
                        tvRestrictAmountRepeat.setTextColor(getResources().getColor(R.color.tc_blue_color));
                        clPayDetail.setVisibility(View.INVISIBLE);
                        tvSellButton.setBackgroundColor(getResources().getColor(R.color.gray_light_bottom_button));
                        tvSellButton.setClickable(false);
                    }
                }
            }
        });

        etMoneyAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!firstEditTextHasFocus) {//本editText获取焦点
                    if (!editable.toString().equals("") || editable.toString().startsWith(".")) {//输入不为""

                        if (!TCStringUtil.inputIsNumber(editable.toString())) {
                            ToastUtil.showToast(SellTCActivity.this, ResStringUtil.getString(R.string.open_planet_asset_selltc_input_illegal));
                            etMoneyAmount.setText("");
                            return;
                        }
                        moneyAmount = new BigDecimal(etMoneyAmount.getText().toString()).doubleValue();
                        //输入的金额除以汇率得到数字币数量，数字币取8位小数
                        ethAmount = TCMathUtil.div(moneyAmount, exchangeRate, 8);
                        etEthAmount.setText(new DecimalFormat("0.00000000").format(TCMathUtil.bigFormat(ethAmount, 8)));
                        if (ethAmount >= minEth && ethAmount <= maxEth) {
                            //如果数字币在限额范围内，则显示底部详情，可以点击购买
                            tvRestrictAmountRepeat.setTextColor(getResources().getColor(R.color.tc_blue_color));
                            clPayDetail.setVisibility(View.VISIBLE);
                            tvMoneyAmount.setText(new DecimalFormat("0.00").format(TCMathUtil.bigFormat(moneyAmount, 2)) + " CNY");
                            tvEthAmount.setText(new DecimalFormat("0.00000000").format(TCMathUtil.bigFormat(ethAmount, 8)) + " "+ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_silver_diamond));
                            tvSellButton.setBackgroundColor(getResources().getColor(R.color.tc_blue_color));
                            tvSellButton.setClickable(true);
                        } else {
                            //数字币不在限额，则“交易限额”显示为红色，底部不可点击
                            tvRestrictAmountRepeat.setTextColor(getResources().getColor(R.color.tc_red_color));
                            clPayDetail.setVisibility(View.INVISIBLE);
                            tvSellButton.setBackgroundColor(getResources().getColor(R.color.gray_light_bottom_button));
                            tvSellButton.setClickable(false);
                        }
                    } else {//输入为"",则不进行数值计算，数字币数量也设为"",限额、底部都设为默认
                        etEthAmount.setText("");
                        tvRestrictAmountRepeat.setTextColor(getResources().getColor(R.color.tc_blue_color));
                        clPayDetail.setVisibility(View.INVISIBLE);
                        tvSellButton.setBackgroundColor(getResources().getColor(R.color.gray_light_bottom_button));
                        tvSellButton.setClickable(false);
                    }
                }

            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_buy) {
            showConfirmWindow();
        } else if (id == R.id.tv_payment_choose || id == R.id.iv_more) {
            showChooseDialog();
        }
    }

    private void showConfirmWindow() {
        View contentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        contentView = inflater.inflate(R.layout.talk_chain_popup_confirm_order, null);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        purchasePopup = new PopupWindow(contentView,
                screenWidth / 6 * 5, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        TextView tvAbort = contentView.findViewById(R.id.tv_abort_purchase);
        tvAbort.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_give_up_selling));
        TextView tvResume = contentView.findViewById(R.id.tv_purchase);
        tvResume.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_confirm_sale));
        TextView tvPrice = contentView.findViewById(R.id.tv_price_amount);
        TextView tvMoneyAmount = contentView.findViewById(R.id.tv_all_amount);
        TextView tvEthAmount = contentView.findViewById(R.id.tv_eth_amount);
        tvPrice.setText(new DecimalFormat("0.00").format(exchangeRate) + " CNY");
        tvMoneyAmount.setText(new DecimalFormat("0.00").format(moneyAmount) + " CNY");
        tvEthAmount.setText(new DecimalFormat("0.00000000").format(ethAmount) + ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_silver_diamond));
        TextView tvPriceIntro = contentView.findViewById(R.id.tv_price);
        tvPriceIntro.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_sale_price));
        TextView tvMoneyAmountIntro = contentView.findViewById(R.id.tv_amount);
        tvMoneyAmountIntro.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_sell_amount));
        TextView tvEthAmountIntro = contentView.findViewById(R.id.tv_eth);
        tvEthAmountIntro.setText(ResStringUtil.getString(R.string.open_planet_asset_selltc_sale_quantity));
        tvAbort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                purchasePopup.dismiss();

            }
        });
        tvResume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                purchasePopup.dismiss();
            }
        });
        purchasePopup.setContentView(contentView);
        purchasePopup.setFocusable(false);
        purchasePopup.setBackgroundDrawable(new BitmapDrawable());
        purchasePopup.setOutsideTouchable(false);
        purchasePopup.showAtLocation(this.findViewById(R.id.title), Gravity.CENTER, 0, 0);
        setBackgroundAlpha(0.5f);
        purchasePopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (purchasePopup != null && purchasePopup.isShowing()) {
            return false;
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = this.getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        this.getWindow().setAttributes(lp);
    }

    private void showChooseDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final String[] items = {ResStringUtil.getString(R.string.open_planet_we_chat), ResStringUtil.getString(R.string.open_planet_pay_for)};
        final int checkedItem = paymentMethod.equals(ResStringUtil.getString(R.string.open_planet_we_chat)) ? 0 : 1;
        builder
                .setTitle(ResStringUtil.getString(R.string.open_planet_asset_selltc_choose_trading_method))
                .setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        paymentMethod = items[i];
                        tvPayment.setText(paymentMethod);
                        dialogInterface.dismiss();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
